import express from 'express';
import cors from 'cors';
import axios from 'axios';
import * as cheerio from 'cheerio';
import winston from 'winston';
import fs from 'fs';
import path from 'path';

const app = express();

// 初始化日志系统
const __dirname = path.resolve();
const logDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir);

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ 
      filename: path.join(logDir, 'combined.log'),
      maxsize: 1024 * 1024 * 5 // 5MB
    })
  ]
});

// 请求日志中间件
app.use((req, res, next) => {
  logger.info({
    message: 'Request received',
    method: req.method,
    path: req.path,
    query: req.query,
    body: req.body,
    timestamp: new Date().toISOString()
  });
  next();
});

app.use(cors());
app.use(express.json());

// 网页内容抓取路由
app.post('/api/scrape', async (req, res) => {
  try {
    const { url } = req.body;
    const response = await axios.get(url);
    const $ = cheerio.load(response.data);
    
    // 提取正文内容
    const content = $('body').text().replace(/\s+/g, ' ').trim();
    res.json({ content: content.slice(0, 5000) });
  } catch (error) {
    logger.info('网页抓取请求', {
  url: req.body.url,
  client: req.ip,
  userAgent: req.headers['user-agent']
});

logger.error('网页抓取失败', { 
  error: error.message,
  stack: error.stack,
  request: {
    method: req.method,
    path: req.path,
    url: req.body.url,
    headers: {
      ...req.headers,
      Authorization: '***'
    }
  }
});
    res.status(500).json({ error: '内容解析服务不可用' });
  }
});

// Bing网页搜索代理路由
app.post('/api/bing-web', async (req, res) => {
  try {
    const { q } = req.body;
    const response = await axios.get(`https://www.bing.com/search?q=${encodeURIComponent(q)}`, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      }
    });

    const html = response.data;
    logger.debug('Bing原始响应', { html: html.slice(0, 2000) });
    const $ = cheerio.load(html);
    logger.debug('Bing页面结构解析', { 
      titleCount: $('h2').length,
      algoCount: $('.b_algo').length,
      captionCount: $('.b_caption').length 
    });
    const results = [];

    $('li.b_algo, .b_algo').each((index, element) => {
      const title = $(element).find('h2').text().trim();
      const url = $(element).find('a').attr('href');
      const snippet = $(element).find('.b_caption p').text().trim();

      if (title && url) {
        results.push({ 
          name: title,
          url: url,
          snippet: snippet 
        });
      }
    });

    logger.info('Bing搜索成功', {
      query: q,
      resultCount: results.length,
      results: results.map(r => ({ title: r.name, url: r.url })),
      timestamp: new Date().toISOString()
    });
    res.json(results);
  } catch (error) {
    logger.error('Bing搜索失败', {
  error: error.message,
  stack: error.stack,
  request: {
    method: req.method,
    path: req.path,
    query: req.query,
    body: req.body,
    headers: {
      ...req.headers,
      Authorization: '***'
    }
  }
});
    res.status(200).json([]);
  }
});

// 大模型请求路由
app.post('/api/generate', async (req, res) => {
  const { userQuery, webContent } = req.body;
  
    try {
      logger.info('AI请求开始', {
        userQuery: userQuery,
        webContent: webContent,
        client: req.ip
      });
      const startTime = Date.now();
    const response = await axios.post('http://xxxxx:8071/v1/chat/completions', {
      model: "DeepSeek-R1-Distill-Qwen-32B",
      messages: [
        {
          role: "system",
          content: webContent
        },
        {
          role: "user",
          content: userQuery
        }
      ]
    }, {
      headers: {
        'Authorization': `Bearer sk-xxxxx`,
        'Content-Type': 'application/json'
      }
    });

    const duration = Date.now() - startTime;
    logger.info('AI请求成功', {
      responsePreview: response.data.choices[0].message.content.substring(0, 200),
      durationMs: duration,
      statusCode: response.status
    });
    res.json({
      answer: response.data.choices[0].message.content,
      sources: []
    });
  } catch (error) {
    logger.info('AI生成请求', {
      userQuery: req.body.userQuery,
      contentLength: req.body.webContent?.length,
      client: req.ip
    });

    logger.error('AI服务调用失败', {
      error: error.message,
      stack: error.stack,
      request: {
        method: req.method,
        path: req.path,
        body: req.body,
        headers: {
          ...req.headers,
          Authorization: '***'
        }
      }
    });
    res.status(500).json({ error: 'AI服务暂时不可用' });
  }
});

// Ollama 大模型请求路由
app.post('/api/generate-ollama', async (req, res) => {
  const { userQuery, webContent } = req.body;
  
  try {
    logger.info('Ollama AI请求开始', {
      userQuery: userQuery,
      webContent: webContent,
      client: req.ip
    });
    
    const startTime = Date.now();
    const response = await axios.post('http://127.0.0.1:11434/api/chat', {
      model: "deepseek-r1:7b",  
      messages: [
        {
          role: "system",
          content: `你是一个智能搜索助手。基于以下网页内容回答用户的问题：\n${webContent}`
        },
        {
          role: "user",
          content: userQuery
        }
      ],
      stream: false
    });

    const duration = Date.now() - startTime;
    logger.info('Ollama AI请求成功', {
      responsePreview: response.data.message.content.substring(0, 200),
      durationMs: duration,
      model: "mistral"
    });
    
    res.json({
      answer: response.data.message.content,
      sources: []
    });
  } catch (error) {
    logger.error('Ollama AI服务调用失败', {
      error: error.message,
      stack: error.stack,
      request: {
        method: req.method,
        path: req.path,
        query: req.query,
        body: req.body
      }
    });
    res.status(500).json({ error: 'Ollama AI服务暂时不可用' });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});